package com.push.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.push.common.utils.EncryptUtil;
import com.push.common.utils.StringUtils;
import com.push.common.utils.httpclient.HttpClientResult;
import com.push.common.utils.httpclient.HttpClientUtil;
import com.push.web.vo.ToutiaoParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.push.common.annotation.Log;
import com.push.common.core.controller.BaseController;
import com.push.common.core.domain.AjaxResult;
import com.push.common.enums.BusinessType;
import com.push.web.domain.BizToutiaoNews;
import com.push.web.service.IBizToutiaoNewsService;
import com.push.common.utils.poi.ExcelUtil;
import com.push.common.core.page.TableDataInfo;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

/**
 * 头条新闻Controller
 *
 * @author yanxi
 * @date 2022-09-21
 */
@RestController
@RequestMapping("/information/toutiaoNews")
public class BizToutiaoNewsController extends BaseController
{
    @Autowired
    private IBizToutiaoNewsService bizToutiaoNewsService;

    /**
     * 查询头条新闻列表
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizToutiaoNews bizToutiaoNews)
    {
        startPage();
        List<BizToutiaoNews> list = bizToutiaoNewsService.selectBizToutiaoNewsList(bizToutiaoNews);
        return getDataTable(list);
    }

    /**
     * 导出头条新闻列表
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:export')")
    @Log(title = "头条新闻", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BizToutiaoNews bizToutiaoNews)
    {
        List<BizToutiaoNews> list = bizToutiaoNewsService.selectBizToutiaoNewsList(bizToutiaoNews);
        ExcelUtil<BizToutiaoNews> util = new ExcelUtil<BizToutiaoNews>(BizToutiaoNews.class);
        return util.exportExcel(list, "头条新闻数据");
    }

    /**
     * 获取头条新闻详细信息
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(bizToutiaoNewsService.selectBizToutiaoNewsById(id));
    }

    /**
     * 新增头条新闻
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:add')")
    @Log(title = "头条新闻", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizToutiaoNews bizToutiaoNews)
    {
        return toAjax(bizToutiaoNewsService.insertBizToutiaoNews(bizToutiaoNews));
    }

    /**
     * 修改头条新闻
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:edit')")
    @Log(title = "头条新闻", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizToutiaoNews bizToutiaoNews)
    {
        return toAjax(bizToutiaoNewsService.updateBizToutiaoNews(bizToutiaoNews));
    }

    /**
     * 删除头条新闻
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:remove')")
    @Log(title = "头条新闻", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(bizToutiaoNewsService.deleteBizToutiaoNewsByIds(ids));
    }

    /**
     * 修改头条新闻
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:refreshNews')")
    @Log(title = "更新头条新闻", businessType = BusinessType.UPDATE)
    @PutMapping("/refresh")
    public AjaxResult refreshNews(@RequestBody ToutiaoParam toutiaoParam)
    {
        List<String> filterWords = new ArrayList<>();
        filterWords.add("洪水");
        filterWords.add("暴雨");
        filterWords.add("山洪");
        filterWords.add("洪涝");
        filterWords.add("防汛");
        String url = "http://api.tianapi.com/topnews/index";
        HashMap params = new HashMap();
        params.put("key","72938d44a27f03c9182c103c65e6f2f4");
        params.put("num", String.valueOf(toutiaoParam.getPageNum()));
        if(StringUtils.isNotEmpty(toutiaoParam.getKeyword())){
            params.put("word", toutiaoParam.getKeyword());
        }
        for (int page = toutiaoParam.getStartPage(); page <= toutiaoParam.getEndPage(); page++){
            params.put("page", String.valueOf(page));
            HttpClientResult newsResult = HttpClientUtil.doGet(url, params, true);
            JSONObject dataObj = JSONObject.parseObject(newsResult.getContent());
            if (dataObj.getInteger("code").equals(200)){
                JSONArray newslist = dataObj.getJSONArray("newslist");
                for (int i=0; i<newslist.size(); i++){
                    System.out.println(newslist.getJSONObject(i).getString("title"));
                    BizToutiaoNews bizToutiaoNews = new BizToutiaoNews();
                    bizToutiaoNews.setId(newslist.getJSONObject(i).getString("id"));
                    bizToutiaoNews.setCtime(newslist.getJSONObject(i).getDate("ctime"));
                    bizToutiaoNews.setTitle(newslist.getJSONObject(i).getString("title"));
                    if(newslist.getJSONObject(i).containsKey("description")){
                        bizToutiaoNews.setDescription(newslist.getJSONObject(i).getString("description"));
                    }
                    if(newslist.getJSONObject(i).containsKey("picUrl")){
                        bizToutiaoNews.setPicUrl(newslist.getJSONObject(i).getString("picUrl"));
                    }
                    if(newslist.getJSONObject(i).containsKey("url")){
                        bizToutiaoNews.setUrl(newslist.getJSONObject(i).getString("url"));
                    }
                    if(newslist.getJSONObject(i).containsKey("source")){
                        bizToutiaoNews.setSource(newslist.getJSONObject(i).getString("source"));
                    }
                    BizToutiaoNews dbizToutiaoNews = bizToutiaoNewsService.selectBizToutiaoNewsById(bizToutiaoNews.getId());
                    if (StringUtils.isNull(dbizToutiaoNews)){
                        bizToutiaoNewsService.insertBizToutiaoNews(bizToutiaoNews);
                    } else {
                        System.out.println(bizToutiaoNews.toString());
                    }
                    /*
                    if (StringUtils.strContains(newslist.getJSONObject(i).getString("title"),filterWords)){

                    }*/
                }
            } else {
                System.out.println(dataObj.getInteger("code")+":"+dataObj.getInteger("msg"));
                return AjaxResult.success();
            }
            try {
                Thread.sleep(toutiaoParam.getThreadTime()*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改头条新闻
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:refreshNews')")
    @Log(title = "更新头条新闻", businessType = BusinessType.UPDATE)
    @PutMapping("/mxnzp")
    public AjaxResult mxnzp(@RequestBody ToutiaoParam toutiaoParam)
    {
        String url = "https://www.mxnzp.com/api/news/list";
        HashMap params = new HashMap();
        params.put("app_id","72938d44a27f03c9182c103c65e6f2f4");
        params.put("app_secret","SW4yZ1ZVMlh3U01wTTRES29HME8rQT09");
        params.put("num", String.valueOf(toutiaoParam.getPageNum()));
        if(StringUtils.isNotEmpty(toutiaoParam.getKeyword())){
            params.put("word", toutiaoParam.getKeyword());
        }
        for (int page = toutiaoParam.getStartPage(); page <= toutiaoParam.getEndPage(); page++){
            params.put("page", String.valueOf(page));
            HttpClientResult newsResult = HttpClientUtil.doGet(url, params, true);
            JSONObject dataObj = JSONObject.parseObject(newsResult.getContent());
            if (dataObj.getInteger("code").equals(200)){
                JSONArray newslist = dataObj.getJSONArray("newslist");
                for (int i=0; i<newslist.size(); i++){
                    System.out.println(newslist.getJSONObject(i).getString("title"));
                    BizToutiaoNews bizToutiaoNews = new BizToutiaoNews();
                    bizToutiaoNews.setId(newslist.getJSONObject(i).getString("id"));
                    bizToutiaoNews.setCtime(newslist.getJSONObject(i).getDate("ctime"));
                    bizToutiaoNews.setTitle(newslist.getJSONObject(i).getString("title"));
                    if(newslist.getJSONObject(i).containsKey("description")){
                        bizToutiaoNews.setDescription(newslist.getJSONObject(i).getString("description"));
                    }
                    if(newslist.getJSONObject(i).containsKey("picUrl")){
                        bizToutiaoNews.setPicUrl(newslist.getJSONObject(i).getString("picUrl"));
                    }
                    if(newslist.getJSONObject(i).containsKey("url")){
                        bizToutiaoNews.setUrl(newslist.getJSONObject(i).getString("url"));
                    }
                    if(newslist.getJSONObject(i).containsKey("source")){
                        bizToutiaoNews.setSource(newslist.getJSONObject(i).getString("source"));
                    }
                    BizToutiaoNews dbizToutiaoNews = bizToutiaoNewsService.selectBizToutiaoNewsById(bizToutiaoNews.getId());
                    if (StringUtils.isNull(dbizToutiaoNews)){
                        bizToutiaoNewsService.insertBizToutiaoNews(bizToutiaoNews);
                    } else {
                        System.out.println(bizToutiaoNews.toString());
                    }
                    /*
                    if (StringUtils.strContains(newslist.getJSONObject(i).getString("title"),filterWords)){

                    }*/
                }
            } else {
                System.out.println(dataObj.getInteger("code")+":"+dataObj.getInteger("msg"));
            }
            try {
                Thread.sleep(toutiaoParam.getThreadTime()*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改头条新闻
     */
    @PreAuthorize("@ss.hasPermi('information:toutiaoNews:refreshNews')")
    @Log(title = "更新头条新闻", businessType = BusinessType.UPDATE)
    @PutMapping("/wayjd")
    public AjaxResult wayjd(@RequestBody ToutiaoParam toutiaoParam)
    {
        String url = "https://way.jd.com/jisuapi/get";
        HashMap params = new HashMap();
        //channel=新闻&num=40&start=0&appkey=283158cb860c9d5435e8825d5a9c08c1
        params.put("appkey","283158cb860c9d5435e8825d5a9c08c1");
        params.put("num", String.valueOf(toutiaoParam.getPageNum()));
        if(StringUtils.isNotEmpty(toutiaoParam.getKeyword())){
            params.put("channel", toutiaoParam.getKeyword());
        } else {
            params.put("channel", "头条");
        }
        for (int page = toutiaoParam.getStartPage(); page <= toutiaoParam.getEndPage(); page++){
            params.put("start", String.valueOf(page * toutiaoParam.getPageNum()));
            HttpClientResult newsResult = HttpClientUtil.doGet(url, params, true);
            JSONObject dataObj = JSONObject.parseObject(newsResult.getContent());
            if (dataObj.getInteger("code").equals(10000)){
                JSONArray newslist = dataObj.getJSONObject("result").getJSONObject("result").getJSONArray("list");
                for (int i=0; i<newslist.size(); i++){
                    System.out.println(newslist.getJSONObject(i).getString("title"));
                    BizToutiaoNews bizToutiaoNews = new BizToutiaoNews();
                    bizToutiaoNews.setCtime(newslist.getJSONObject(i).getDate("time"));
                    bizToutiaoNews.setTitle(newslist.getJSONObject(i).getString("title"));
                    if(newslist.getJSONObject(i).containsKey("content")){
                        bizToutiaoNews.setContents(newslist.getJSONObject(i).getString("content"));
                    }
                    if(newslist.getJSONObject(i).containsKey("pic")){
                        bizToutiaoNews.setPicUrl(newslist.getJSONObject(i).getString("pic"));
                    }
                    if(newslist.getJSONObject(i).containsKey("weburl")){
                        bizToutiaoNews.setUrl(newslist.getJSONObject(i).getString("weburl"));
                    }
                    if(newslist.getJSONObject(i).containsKey("src")){
                        bizToutiaoNews.setSource(newslist.getJSONObject(i).getString("src"));
                    }
                    bizToutiaoNews.setId(EncryptUtil.encrypt(bizToutiaoNews.getUrl(), "md5"));
                    BizToutiaoNews dbizToutiaoNews = bizToutiaoNewsService.selectBizToutiaoNewsById(bizToutiaoNews.getId());
                    if (StringUtils.isNull(dbizToutiaoNews)){
                        bizToutiaoNewsService.insertBizToutiaoNews(bizToutiaoNews);
                    } else {
                        System.out.println(bizToutiaoNews.toString());
                    }
                    /*
                    if (StringUtils.strContains(newslist.getJSONObject(i).getString("title"),filterWords)){

                    }*/
                }
            } else {
                System.out.println(dataObj.getInteger("code")+":"+dataObj.getInteger("msg"));
            }
            try {
                Thread.sleep(toutiaoParam.getThreadTime()*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success();
    }
}
